package com.myNovel.novel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myNovel.novel.core.common.constant.DatabaseConstants;
import com.myNovel.novel.core.common.constant.ErrorCodeEnum;
import com.myNovel.novel.core.common.resp.RestResp;
import com.myNovel.novel.dao.entity.BookComment;
import com.myNovel.novel.dao.entity.UserInfo;
import com.myNovel.novel.dao.mapper.BookCommentMapper;
import com.myNovel.novel.dao.mapper.BookInfoMapper;
import com.myNovel.novel.dto.req.UserCommentReqDto;
import com.myNovel.novel.dto.resp.BookCommentRespDto;
import com.myNovel.novel.manager.UserDaoManager;
import com.myNovel.novel.service.BookService;
import lombok.RequiredArgsConstructor;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author：Guxx
 * @Package：com.myNovel.novel.service.impl
 * @Date：2024/3/30 16:35
 * @Filename：BookServiceImpl
 */
@Service
@RequiredArgsConstructor
public class BookServiceImpl implements BookService {
    private final BookCommentMapper bookCommentMapper;
    private final UserDaoManager userDaoManager;
    @Override
    public RestResp<Void> saveComment(UserCommentReqDto dto) {
        //校验用户是否已发表评论
        QueryWrapper<BookComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DatabaseConstants.BookCommentTable.COLUMN_USER_ID,dto.getUserId())
                .eq(DatabaseConstants.BookCommentTable.COLUMN_BOOK_ID,dto.getBookId());
        if (bookCommentMapper.selectCount(queryWrapper) > 0){
            //用户已经发表评论
            return RestResp.fail(ErrorCodeEnum.USER_COMMENTED);
        }

        BookComment bookComment = new BookComment();
        bookComment.setBookId(dto.getBookId());
        bookComment.setUserId(dto.getUserId());
        bookComment.setCommentContent(dto.getCommentContent());
        bookComment.setCreateTime(LocalDateTime.now());
        bookComment.setUpdateTime(LocalDateTime.now());
        return RestResp.ok();
    }

    @Override
    public RestResp<Void> updateComment(Long userId, Long id, String content) {
        QueryWrapper<BookComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DatabaseConstants.CommonColumnEnum.ID.getName(),id)
                .eq(DatabaseConstants.BookCommentTable.COLUMN_USER_ID,userId);

        BookComment bookComment = new BookComment();
        bookComment.setCommentContent(content);
        bookComment.setUpdateTime(LocalDateTime.now());
        return RestResp.ok();
    }
    @Override
    public RestResp<Void> deleteComment(Long userId,Long commentId){
        QueryWrapper<BookComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DatabaseConstants.CommonColumnEnum.ID.getName(),commentId)
                .eq(DatabaseConstants.BookCommentTable.COLUMN_USER_ID,userId);
        bookCommentMapper.delete(queryWrapper);
        return RestResp.ok();
    }

    @Override
    public RestResp<BookCommentRespDto> listNewestComments(Long bookId) {
        QueryWrapper<BookComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DatabaseConstants.BookCommentTable.COLUMN_BOOK_ID,bookId);
        Long commentTotal = bookCommentMapper.selectCount(queryWrapper);
        BookCommentRespDto bookCommentRespDto = BookCommentRespDto.builder().commentTotal(commentTotal).build();
        if (commentTotal > 0){
            //查询最新的评论列表
            QueryWrapper<BookComment> commentQueryWrapper = new QueryWrapper<>();
            commentQueryWrapper.eq(DatabaseConstants.BookCommentTable.COLUMN_BOOK_ID,bookId)
                    .orderByDesc(DatabaseConstants.CommonColumnEnum.CREATE_TIME.getName())
                    .last(DatabaseConstants.SqlEum.LIMIT_5.getSql());
            List<BookComment> bookComments = bookCommentMapper.selectList(commentQueryWrapper);

            // 查询评论用户信息，并设置需要返回的评论用户名
            List<Long> userIds = bookComments.stream().map(BookComment::getUserId).toList();
            List<UserInfo>  userInfos = userDaoManager.listUsers(userIds);
            Map<Long, String> userInfoMap = userInfos.stream().collect(Collectors.toMap(UserInfo::getId,UserInfo::getUsername));
            List<BookCommentRespDto.CommentInfo> commentInfos = bookComments.stream()
                    .map(v ->BookCommentRespDto.CommentInfo.builder()
                            .id(v.getId())
                            .commentUserId(v.getUserId())
                            .commentUser(userInfoMap.get(v.getUserId()))
                            .commentContent(v.getCommentContent())
                            .commentTime(v.getCreateTime()).build()
                    ).toList();
            bookCommentRespDto.setComments(commentInfos);
        }else {
            bookCommentRespDto.setComments(Collections.emptyList());
        }
        return RestResp.ok(bookCommentRespDto);
    }
}
